/**
 * 聊天室功能模块
 */

// WebSocket连接变量
let socket;
let users = [];

// DOM元素引用
let messageInput;
let sendButton;
let messageContainer;
let usersList;
let onlineCount;
let connectionStatus;
let usersPanel;
let usersHeader;
let emojiButton;
let emojiPicker;
let closeEmojiPicker;

/**
 * 初始化聊天室背景
 * @param {string} chatRoomBackground - 背景图片URL
 * @param {string} chatRoomBackgroundOpacity - 背景透明度
 */
function initializeBackground(chatRoomBackground, chatRoomBackgroundOpacity) {
    console.log("应用聊天室背景: " + chatRoomBackground + ", 透明度: " + chatRoomBackgroundOpacity);
    
    if (chatRoomBackground && chatRoomBackground.trim() !== '') {
        // 添加背景图片类
        document.body.classList.add('has-bg-image');
        
        // 设置背景图片
        document.body.style.backgroundImage = `url('${chatRoomBackground}')`;
        
        // 设置覆盖层透明度
        const overlay = document.getElementById('bgOverlay');
        if (overlay) {
            overlay.style.backgroundColor = `rgba(26, 31, 37, ${chatRoomBackgroundOpacity})`;
        }
        
        // 移动设备上使用更高的不透明度以提高可读性
        if (window.innerWidth <= 768) {
            const mobileOpacity = Math.min(parseFloat(chatRoomBackgroundOpacity) + 0.2, 0.95);
            if (overlay) {
                overlay.style.backgroundColor = `rgba(26, 31, 37, ${mobileOpacity})`;
            }
        }
        
        // 聊天室容器样式适配
        const chatRoomContainer = document.querySelector('.chat-room-container');
        if (chatRoomContainer) {
            chatRoomContainer.style.boxShadow = 'none';
            chatRoomContainer.style.border = 'none';
            chatRoomContainer.style.backgroundColor = 'rgba(0, 0, 0, 0)';
        }
        
        // 窗口大小变化时调整背景透明度
        window.addEventListener('resize', function() {
            if (overlay) {
                if (window.innerWidth <= 768) {
                    // 在移动设备上增加不透明度
                    const mobileOpacity = Math.min(parseFloat(chatRoomBackgroundOpacity) + 0.2, 0.95);
                    overlay.style.backgroundColor = `rgba(26, 31, 37, ${mobileOpacity})`;
                } else {
                    // 在桌面恢复原始透明度
                    overlay.style.backgroundColor = `rgba(26, 31, 37, ${chatRoomBackgroundOpacity})`;
                }
            }
        });
    } else {
        console.log("没有设置背景图片，使用默认背景");
    }
}

/**
 * 初始化聊天室
 * @param {Object} currentUser - 当前登录用户信息
 */
function initializeChat(currentUser) {
    // 获取DOM元素
    messageInput = document.getElementById('messageInput');
    sendButton = document.getElementById('sendButton');
    messageContainer = document.getElementById('messageContainer');
    usersList = document.getElementById('usersList');
    onlineCount = document.getElementById('onlineCount');
    connectionStatus = document.getElementById('connectionStatus');
    usersPanel = document.querySelector('.users-panel');
    usersHeader = document.querySelector('.users-header');
    emojiButton = document.getElementById('emojiButton');
    emojiPicker = document.getElementById('emojiPicker');
    closeEmojiPicker = document.getElementById('closeEmojiPicker');
    
    // 移动端用户列表折叠功能
    if (window.innerWidth <= 768) {
        usersPanel.classList.add('collapsed');
        
        usersHeader.addEventListener('click', function() {
            usersPanel.classList.toggle('collapsed');
        });
    }
    
    // 监听窗口大小变化
    window.addEventListener('resize', function() {
        if (window.innerWidth <= 768) {
            if (!usersHeader.hasEventListener) {
                usersHeader.addEventListener('click', function() {
                    usersPanel.classList.toggle('collapsed');
                });
                usersHeader.hasEventListener = true;
            }
        } else {
            usersPanel.classList.remove('collapsed');
        }
    });
    
    // 表情选择器事件处理
    initializeEmojiPicker();
    
    // 连接WebSocket
    connectWebSocket();
    
    // 发送按钮点击事件
    sendButton.addEventListener('click', sendMessage);
    
    // 输入框回车事件
    messageInput.addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            sendMessage();
        }
    });
    
    // 输入框内容变化事件
    messageInput.addEventListener('input', function() {
        sendButton.disabled = messageInput.value.trim() === '';
    });
    
    // 初始滚动到底部
    scrollToBottom();
}

/**
 * 初始化表情选择器
 */
function initializeEmojiPicker() {
    // 表情按钮点击事件
    emojiButton.addEventListener('click', function(e) {
        e.stopPropagation(); // 阻止事件冒泡
        toggleEmojiPicker();
    });
    
    // 关闭按钮点击事件
    closeEmojiPicker.addEventListener('click', function() {
        hideEmojiPicker();
    });
    
    // 选择表情事件
    const emojiItems = document.querySelectorAll('.emoji-item');
    emojiItems.forEach(item => {
        item.addEventListener('click', function() {
            insertEmoji(this.textContent);
            hideEmojiPicker();
        });
    });
    
    // 点击页面其他区域关闭表情选择器
    document.addEventListener('click', function(e) {
        if (!emojiPicker.contains(e.target) && e.target !== emojiButton) {
            hideEmojiPicker();
        }
    });
}

/**
 * 切换表情选择器显示/隐藏
 */
function toggleEmojiPicker() {
    if (emojiPicker.style.display === 'block') {
        hideEmojiPicker();
    } else {
        showEmojiPicker();
    }
}

/**
 * 显示表情选择器
 */
function showEmojiPicker() {
    emojiPicker.style.display = 'block';
    
    // 确保表情选择器在视口范围内
    const pickerRect = emojiPicker.getBoundingClientRect();
    const viewportHeight = window.innerHeight;
    
    if (pickerRect.bottom > viewportHeight) {
        emojiPicker.style.bottom = 'auto';
        emojiPicker.style.top = '-310px';
    }
}

/**
 * 隐藏表情选择器
 */
function hideEmojiPicker() {
    emojiPicker.style.display = 'none';
    // 重置位置设置
    emojiPicker.style.bottom = '80px';
    emojiPicker.style.top = 'auto';
}

/**
 * 在输入框插入表情
 * @param {string} emoji - 表情字符
 */
function insertEmoji(emoji) {
    const startPos = messageInput.selectionStart;
    const endPos = messageInput.selectionEnd;
    const text = messageInput.value;
    const newText = text.substring(0, startPos) + emoji + text.substring(endPos);
    
    messageInput.value = newText;
    messageInput.focus();
    messageInput.selectionStart = messageInput.selectionEnd = startPos + emoji.length;
    
    // 更新发送按钮状态
    sendButton.disabled = messageInput.value.trim() === '';
}

/**
 * 连接WebSocket
 */
function connectWebSocket() {
    const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
    const host = window.location.host;
    socket = new WebSocket(`${protocol}//${host}/ws/chat`);
    
    // 连接建立时
    socket.onopen = function() {
        connectionStatus.textContent = '已连接';
        connectionStatus.style.color = '#48bb78';
        
        // 发送加入消息
        const joinMessage = {
            type: 'JOIN',
            sender: currentUser.username,
            content: '加入了聊天室'
        };
        socket.send(JSON.stringify(joinMessage));
    };
    
    // 接收消息时
    socket.onmessage = function(event) {
        const message = JSON.parse(event.data);
        
        switch (message.type) {
            case 'CHAT':
                addMessage(message);
                break;
            case 'JOIN':
                addSystemMessage(`${message.sender} 加入了聊天室`);
                updateUserList(message.users);
                break;
            case 'LEAVE':
                addSystemMessage(`${message.sender} 离开了聊天室`);
                updateUserList(message.users);
                break;
            case 'USERS':
                updateUserList(message.users);
                break;
        }
        
        // 滚动到底部
        scrollToBottom();
    };
    
    // 连接关闭时
    socket.onclose = function(event) {
        connectionStatus.textContent = '连接已断开';
        connectionStatus.style.color = '#e53e3e';
        
        console.log("WebSocket连接已关闭: ", event);
        
        // 5秒后尝试重新连接
        setTimeout(connectWebSocket, 5000);
    };
    
    // 连接出错时
    socket.onerror = function(error) {
        console.error('WebSocket错误:', error);
        connectionStatus.textContent = '连接错误';
        connectionStatus.style.color = '#e53e3e';
    };
}

/**
 * 发送消息
 */
function sendMessage() {
    const content = messageInput.value.trim();
    if (content === '') return;
    
    const chatMessage = {
        type: 'CHAT',
        sender: currentUser.username,
        content: content,
        time: new Date().toISOString()
    };
    
    socket.send(JSON.stringify(chatMessage));
    messageInput.value = '';
    sendButton.disabled = true;
}

/**
 * 添加消息到聊天窗口
 * @param {Object} message - 消息对象
 */
function addMessage(message) {
    const isOwnMessage = message.sender === currentUser.username;
    const messageElement = document.createElement('div');
    messageElement.className = `message ${isOwnMessage ? 'own' : ''}`;
    
    const avatar = message.avatar || '/images/default-avatar.svg';
    const time = new Date(message.time).toLocaleTimeString();
    
    messageElement.innerHTML = `
        <img src="${avatar}" alt="${message.sender}" class="message-avatar">
        <div class="message-content">
            <p class="message-text">${message.content}</p>
            <p class="message-time">${message.sender} · ${time}</p>
        </div>
    `;
    
    messageContainer.appendChild(messageElement);
}

/**
 * 添加系统消息
 * @param {string} text - 系统消息文本
 */
function addSystemMessage(text) {
    const messageElement = document.createElement('div');
    messageElement.className = 'system-message';
    messageElement.innerHTML = `<p>${text}</p>`;
    messageContainer.appendChild(messageElement);
}

/**
 * 更新用户列表
 * @param {Array} newUsers - 用户列表
 */
function updateUserList(newUsers) {
    users = newUsers;
    usersList.innerHTML = '';
    onlineCount.textContent = users.length;
    
    users.forEach(user => {
        const userElement = document.createElement('div');
        userElement.className = 'user-item';
        
        const avatar = user.avatar || '/images/default-avatar.svg';
        
        userElement.innerHTML = `
            <img src="${avatar}" alt="${user.username}" class="user-avatar">
            <div class="user-info">
                <p class="user-name">${user.username}</p>
                <p class="user-status online">在线</p>
            </div>
        `;
        
        usersList.appendChild(userElement);
    });
}

/**
 * 滚动到底部
 */
function scrollToBottom() {
    messageContainer.scrollTop = messageContainer.scrollHeight;
}

// 导出初始化函数
window.chatRoom = {
    initializeBackground,
    initializeChat
}; 